import {getTimestamp} from "@/units/time";

type CacheValue = { value: any, exp: number }

/**
 * 获取缓存前缀
 */
function prefix(): string {
    let pathname: string = location.pathname.replace('.html', '')
    if (pathname.length === 0 || pathname === '/') {
        return 'index'
    }
    let paths: Array<string> = pathname.split('/')
    let peffix: any = paths.pop()
    if (typeof peffix === 'string' && peffix.length > 0) {
        return peffix
    }
    return 'index'
}

/**
 * 获取缓存KEY
 * @param key
 */
function getKey(key: string): string {
    return prefix() + ':' + key
}


/**
 * 设置缓存
 * @param key 键值
 * @param value 内容
 * @param exp  有效期
 */
function set(key: string, value: any, exp: number = 10000000) {
    let data: CacheValue = {value: value, exp: getTimestamp() + exp * 1000}
    localStorage.setItem(getKey(key), JSON.stringify(data))
}


/**
 * 获取缓数据
 * @param key
 * @param def
 */
function get(key: string, def: any = null): any {
    try {
        let value: any = localStorage.getItem(getKey(key))
        if (value === null) {
            return def
        }
        let json = JSON.parse(value)
        if (typeof json.value !== 'undefined' && typeof json.exp !== 'undefined') {
            if (json.exp > getTimestamp()) {
                return json.value
            }
        }
        return def
    } catch (e) {
        return def
    }
}


/**
 * 删除缓存
 * @param key
 */
function del(key: string) {
    localStorage.removeItem(getKey(key))
}


/**
 * 清空缓存
 */
function clear() {
    let kyes: string[] = Object.keys(localStorage)
    let prefix_name = prefix() + ':'
    for (let key of kyes) {
        if (key.substring(0, prefix_name.length) === prefix_name) {
            localStorage.removeItem(key)
        }
    }
}

export default {prefix, set, get, del, clear}